package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.advice.CostomReturnException;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.BaseEntity;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.jsonwebtoken.Claims;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private SystemUserService systemUserService;

    @Override
    public CaptchaVo customGetCaptcha() {

        //生成四位数数字字母组合的图片验证码
        SpecCaptcha specCaptcha = new SpecCaptcha(130,48,4);//生成图片大小，验证码位数
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);//生成规则,字母加数字
        //转加密字符串
        String base64 = specCaptcha.toBase64();
        //获取4位验证码内容
        String text = specCaptcha.text();

        //将验证码保存到redis，设置redis保存时长60s
        String uuid = UUID.randomUUID().toString().replaceAll("_", "");//生成一个uuid做redis的key
        String uuidKey = RedisConstant.ADMIN_LOGIN_PREFIX + uuid;//加前缀，完整key
        redisTemplate.opsForValue().set(uuidKey,text,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);

        //返回给前端验证码数据以及key
        return new CaptchaVo(base64,uuidKey);
    }

    @Override
    public String customLogin(LoginVo loginVo) {
        LambdaQueryWrapper<SystemUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SystemUser::getUsername,loginVo.getUsername());
        SystemUser systemUser = systemUserService.getOne(lambdaQueryWrapper);
        //验证用户名是否存在
        if (systemUser ==null){
            //用户错误执行
            throw new CostomReturnException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //验证密码是否正确
        if (systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))) {
            //密码不正确，抛出异常
            throw new CostomReturnException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //验证验证码是否为空
        String s = (String) redisTemplate.opsForValue().get(loginVo.getCaptchaKey()); //获取存储的验证码
        if (loginVo.getCaptchaCode() ==null){
            throw new CostomReturnException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        //验证码是否过期
        if (s ==null){
            throw new CostomReturnException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //验证码是否对
        if (s.equals(loginVo.getCaptchaCode())){
            throw  new CostomReturnException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //验证账户是否有效
        if (systemUser.getStatus() == BaseStatus.DISABLE) {
            throw new CostomReturnException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //验证通过生成token
        return JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
    }

    @Override
    public SystemUserInfoVo customInfo(String accessToken) {
        //验证token
        Claims claims = JwtUtil.parseToken(accessToken);
        Integer id = (Integer) claims.get("userId");
        //无效
        SystemUser systemUser = systemUserService.getById(id);
        if (systemUser == null) {
            throw new CostomReturnException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }
}
